import { Client, Databases, ID, Storage, Query } from 'appwrite'
import { Server } from '@configs/server.js'
import { activityStatus } from '../utility/constant'

const client = new Client()
  .setEndpoint(Server.endpoint)
  .setProject(Server.project)
const databases = new Databases(client)
const storage = new Storage(client)

/** 上传文件**/
export const uploadFile = async (files) => {
  return await storage.createFile(Server.BUCKET_ID, ID.unique(), files)
}

/** 文件预览**/
export const previewFileApi = () => {
  return storage.getFilePreview(Server.BUCKET_ID, '650eca072a5d0ce7c005')
}

/** 创建活动**/
export const createActivityApi = async (data) => {
  return await databases.createDocument(
    Server.databaseID,
    Server.collection_partyId,
    ID.unique(),
    data
  )
}

/**
 * 活动列表
 * @param {*} q 搜索内容
 * @param {*} perPage 每页数量
 * @param {*} offsetPage 当前页数*每页数量
 * @returns
 */
export const activityListApi = async ({ q, perPage, offsetPage }) => {
  let condition = [Query.limit(perPage), Query.offset(offsetPage)]
  if (!q) {
    condition = [...condition]
  } else {
    condition = [...condition, Query.search('name', q)]
  }
  const res = await databases.listDocuments(
    Server.databaseID,
    Server.collection_partyId,
    condition
  )
  const list =
    res &&
    res.documents.map((item) => {
      let status
      // 获取当前时间戳
      const timestamp = Date.now()
      if (timestamp < item.startTime) {
        status = {
          label: '未开始',
          value: Object.keys(activityStatus)[2],
        }
      } else if (timestamp > item.startTime && timestamp < item.endTime) {
        status = {
          label: '进行中',
          value: Object.keys(activityStatus)[1],
        }
      } else {
        status = {
          label: '已结束',
          value: Object.keys(activityStatus)[0],
        }
      }
      return { ...item, status }
    })

  return { ...res, documents: list }
}

/** 获取干部列表 */

/** 获取活动详情 */
export const getDetailApi = async ($id) => {
  return await databases.getDocument(
    Server.databaseID,
    Server.collection_partyId,
    $id
  )
}

/** 编辑列表 */
export const editActivityApi = async ($id, data) => {
  return await databases.updateDocument(
    Server.databaseID,
    Server.collection_partyId,
    $id,
    data
  )
}

/** 删除列表 */
export const deleteActivityApi = async ($id) => {
  return await databases.deleteDocument(
    Server.databaseID,
    Server.collection_partyId,
    $id
  )
}
